package com.yx.changdao.web.controller;

import com.yx.changdao.common.entity.Article;
import com.yx.changdao.common.entity.ArticleCategory;
import com.yx.changdao.common.entity.GridInfo;
import com.yx.changdao.common.utils.UploadUtils;
import com.yx.changdao.service.ArticleCategoryService;
import com.yx.changdao.service.ArticleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yx.changdao.common.annotation.AutoLog;
import com.yx.changdao.common.annotation.ShiroDesc;
import com.yx.changdao.common.data.Result;
import com.yx.changdao.common.exception.AlertException;
import com.yx.changdao.common.utils.SysConst;
import com.yx.changdao.common.utils.SysUtils;
import com.yx.changdao.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Description: <br/>
 * 文章
 * <p>
 * <br/>
 * @Auther: walter
 * @create 2020/04/10 14:48
 */
@RestController
@RequestMapping("article")
public class ArticleController {

    /**
     * 文章服务
     */
    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleCategoryService articleCategoryService;

    /**
     * 列表
     *
     * @return Result
     */
    @AutoLog
    @GetMapping("/list")
    @RequiresPermissions("article:list")
    @ShiroDesc("新闻:列表")
    public Result list(@RequestParam(value = "page") Long page,
                       @RequestParam(value = "limit", required = false) Integer limit) throws AlertException {
        if (limit == null) {
            limit=SysConst.LIMIT_PAGE;
        }
        if (page == null) {
            page=1L;
        }
        /**
         * 分页配置
         */
        Page<Article> pager = new Page<>(page, limit);
        /**
         * 根据条件查询出集合
         */
        QueryWrapper<Article> queryWrapper = SysUtils.autoCnd(Article.class);
        IPage<Article> departmentPage = this.articleService.pageNex(pager, queryWrapper.orderByDesc(Article.CREATE_TIME));
//        IPage<Article> departmentPage = this.articleService.page(pager,queryWrapper.orderByDesc(Article.CREATE_TIME));

        List<Article> list = departmentPage.getRecords();
        /**
         * 图片地址处理
         */
        list.forEach(t -> {
            t.setImg(UploadUtils.advanceShow(t.getImg()));
        });

        // 获取分页结果集。

        Map<String, Object> map = new HashMap();
        map.put("list", list);
        map.put("pager", departmentPage);
        return Result.ok().data(map);
    }

    /**
     * 添加文章
     *
     * @param
     * @return Result
     */
    @AutoLog
    @PostMapping
    public Result add(@RequestBody @Valid Article article) throws AlertException {

        ArticleCategory one = articleCategoryService.getOne(new QueryWrapper<ArticleCategory>().eq(ArticleCategory.ID, article.getCategoryId()));
        article.setName(one.getName());

        /**
         * 图片地址预处理
         */
        article.setImg(UploadUtils.advanceSave(article.getImg()));

        boolean b = articleService.save(article);

        if (!b) {
            throw new AlertException("文章添加失败");
        }

        return Result.ok("文章添加成功");
    }


    /**
     * 获得指定id 文章。
     *
     * @param
     * @return Result
     */
    @AutoLog
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") String id) throws AlertException {

        Article article = articleService.getById(id);
        article.setImg(UploadUtils.advanceShow(article.getImg()));

        if (article == null) {
            throw new AlertException("未找到相关文章信息");
        }

        return Result.ok().data(article);
    }


    /**
     * 更新文章
     *
     * @param
     * @return Result
     */
    @AutoLog
    @PutMapping
    public Result update(@RequestBody @Valid Article article) throws AlertException {

        /**
         * 图片地址预处理
         */
        article.setImg(UploadUtils.advanceSave(article.getImg()));

        boolean b = articleService.updateById(article);
        if (!b) {
            throw new AlertException("文章更新失败");
        }

        return Result.ok("文章更新成功");
    }


    /**
     * 删除文章
     *
     * @param
     * @return Result
     */
    @AutoLog
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") String id) throws AlertException {
        boolean b = articleService.removeById(id);

        if (!b) {
            throw new AlertException("文章删除失败");
        }

        return Result.ok("删除文章成功");
    }

    /**
     * 根据categoryId查内容
     *
     * @return Result
     */
    @AutoLog
    @GetMapping("/getlistByCategoryId")
    public Result getlistByCategoryId(@RequestParam("categoryId") Integer categoryId) throws AlertException {

        List<Article> list = articleService.list(new QueryWrapper<Article>().eq(Article.CATEGORY_ID, categoryId)
                .orderByDesc(Article.CREATE_TIME));

        list.forEach(t -> {
            t.setImg(UploadUtils.advanceShow(t.getImg()));
        });

        return Result.ok().data(list);

    }

    /**
     * 显示前多少条
     * @param number
     * @return
     * @throws AlertException
     */
    @AutoLog
    @GetMapping("/getlistByNum")
    public Result getlistByNum(@RequestParam("number") Integer number) throws AlertException {
        List<Article> list = articleService.selectList(new QueryWrapper<Article>()
                .orderByDesc(Article.CREATE_TIME).last("limit 0," + number));
       /* List<Article> list = articleService.list(new QueryWrapper<Article>()
                .orderByDesc(Article.CREATE_TIME).last("limit 0," + number));*/

        list.forEach(t -> {
            t.setImg(UploadUtils.advanceShow(t.getImg()));
        });

        return Result.ok().data(list);
    }
}
